<?php
/**
 *  @department : Commercial development.
 *  @description : This file is part of [example].
 *  DZ all rights reserved.
 */

namespace app\common\exception;

use Service\LogService;
use think\exception\Handle;

class ExceptionHandle extends Handle
{
    public function render(\Exception $e)
    {
        if ($e instanceof ParamsException) {
            $code = $e->getCode();
            $message = $e->getMessage();
        } elseif ($e instanceof ValidationException) {
            $code = $e->getCode();
            $message = $e->getMessage();
        } elseif ($e instanceof RuntimeException) {
            $code = $e->getCode();
            $message = $e->getMessage();
        } elseif ($e instanceof ApiException) {
            $code = $e->getCode();
            $message = $e->getMessage();
        } else {
            if (true == config('app_debug')) {
                return parent::render($e);
            }

            //未知错误 -- 不在预设抓取范围内
            $code = $e->getCode() ? $e->getCode() : 500;

            $message = $e->getMessage() ? $e->getMessage() : '服务器内部错误。';

            $this->recordErrorLog($message, $e->getFile());
        }

        //参数实例
        $result = [
            'status' => false,
            'code'   => $code,
            'msg'    => $message,
            'message'=> $message,
        ];

        return json($result);
    }

    private function recordErrorLog($message, $error_file)
    {
        LogService::errorLog('System/ErrorHandler', '系统异常:' . $message, $error_file);
    }
}
